/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.web.dao.support.hbn.interceptor;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import java.io.Serializable;
import java.util.Date;

/**
 * Hibernate 过滤器, 自动填充创建时间,最后修改时间
 *
 * @author vacoor
 * @see org.vacoor.nothing.web.dao.support.hbn.listener.AuditListener
 * @deprecated
 */
@Deprecated
public class AuditInterceptor extends EmptyInterceptor {
    private static final long serialVersionUID = -6723299040900912606L;

    public static final String DEFAULT_CREATED_DATE_ATTRIBUTE_NAME = "createDate";
    public static final String DEFAULT_MODIFIED_DATE_ATTRIBUTE_NAME = "modifyDate";

    private String createdDateAttributeName = DEFAULT_CREATED_DATE_ATTRIBUTE_NAME;
    private String modifiedDateAttributeName = DEFAULT_MODIFIED_DATE_ATTRIBUTE_NAME;

    // 保存数据回调
    @Override
    public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
        Date date = new Date();
        for (int i = 0; i < propertyNames.length; i++) {
            String prop = propertyNames[i];
            if (prop.equals(createdDateAttributeName) || prop.equals(modifiedDateAttributeName)) {
                state[i] = date;
            }
        }
        // 如果修改了则应该返回true
        return true;
    }

    // 更新数据回调
    @Override
    public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
        Date date = new Date();
        for (int i = 0; i < propertyNames.length; i++) {
            if (propertyNames[i].equals(modifiedDateAttributeName)) {
                currentState[i] = date;
            }
        }
        return true;
    }
}
